package com.example.service;

import com.example.action.SmsCommitAction;
import com.example.action.SmsSendSuccessAction;
import com.example.enums.Events;
import com.example.enums.Status;
import com.example.listener.SmsStateMachineListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Service;

import java.util.EnumSet;

@Service
public class SmsStateMachineBuilderImpl implements SmsStateMachineBuilder, BeanFactoryAware {

    private final static String MACHINEID = "smsMachine";

    private BeanFactory beanFactory;

    @Override
    public StateMachine<Status, Events> build() throws Exception {
        StateMachineBuilder.Builder<Status, Events> builder = StateMachineBuilder.builder();

        builder.configureConfiguration()
                .withConfiguration()
                .machineId(MACHINEID)
                .beanFactory(beanFactory)
                .listener(new SmsStateMachineListener());

        builder.configureStates()
                .withStates()
                .initial(Status.READY)
                .states(EnumSet.allOf(Status.class));

        builder.configureTransitions()
                .withExternal()
                .source(Status.READY).target(Status.SUCCESS)
                .event(Events.SUCCESSED)
                .action(new SmsSendSuccessAction())
                .and()
                .withExternal()
                .source(Status.SUCCESS).target(Status.COMMIT)
                .event(Events.COMMITED)
                .action(new SmsCommitAction());

        return builder.build();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
